"""
自定义毛玻璃消息框模块 - 统一的消息框样式
用于替换项目中所有的QMessageBox，提供一致的毛玻璃风格界面
"""

from PySide2.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QPushButton,
                               QLabel, QWidget)
from PySide2.QtCore import Qt, QPropertyAnimation, QEasingCurve, QTimer
from PySide2.QtGui import (QFont, QPainter, QBrush, QColor, QLinearGradient,
                          QRadialGradient)


class GlassmorphismMessageBox(QDialog):
    """通用毛玻璃消息框"""
    
    # 消息类型常量
    INFO = "info"
    WARNING = "warning"
    ERROR = "error"
    QUESTION = "question"
    SUCCESS = "success"
    
    def __init__(self, parent=None, title="提示", message="", msg_type=INFO, buttons=None):
        super().__init__(parent)
        self.msg_type = msg_type
        self.buttons = buttons or ["确定"]
        self.result_value = False
        self.setup_dialog(title)
        self.setup_ui(message)
        self.setup_animations()

    def setup_dialog(self, title):
        """设置对话框基本属性"""
        self.setWindowTitle(title)
        self.setFixedSize(480, 300)
        self.setModal(True)
        self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

    def setup_ui(self, message):
        """设置UI界面"""
        self.main_layout = QVBoxLayout()
        self.main_layout.setContentsMargins(35, 30, 35, 30)
        self.main_layout.setSpacing(25)

        # 应用毛玻璃效果
        self.apply_glassmorphism_effect()

        # 添加顶部间距
        self.main_layout.addSpacing(15)

        # 图标和标题行
        icon_title_layout = QHBoxLayout()
        icon_title_layout.setSpacing(15)

        # 根据消息类型设置图标
        icon_text = self.get_icon_for_type()
        icon_label = QLabel(icon_text)
        icon_label.setStyleSheet("""
            QLabel {
                font-size: 32px;
                background: transparent;
                border: none;
            }
        """)
        icon_title_layout.addWidget(icon_label)

        # 消息内容
        message_label = QLabel(message)
        message_label.setWordWrap(True)
        message_label.setStyleSheet("""
            QLabel {
                color: rgba(255, 255, 255, 0.95);
                font-size: 16px;
                font-weight: 500;
                font-family: 'Microsoft YaHei UI', sans-serif;
                background: transparent;
                border: none;
                line-height: 1.5;
            }
        """)
        icon_title_layout.addWidget(message_label, 1)
        
        self.main_layout.addLayout(icon_title_layout)

        # 添加间距
        self.main_layout.addSpacing(20)

        # 按钮容器
        button_container = QWidget()
        button_container.setStyleSheet("QWidget { background: transparent; border: none; }")
        button_layout = QHBoxLayout(button_container)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(15)

        button_layout.addStretch()

        # 创建按钮
        for i, button_text in enumerate(self.buttons):
            btn = QPushButton(button_text)
            btn.setMinimumSize(110, 45)
            
            if len(self.buttons) == 1 or (len(self.buttons) == 2 and i == 1):
                # 单按钮或第二个按钮使用主要样式
                btn.setStyleSheet(self.get_primary_button_style())
                btn.clicked.connect(self.accept_dialog)
            else:
                # 第一个按钮使用次要样式
                btn.setStyleSheet(self.get_secondary_button_style())
                btn.clicked.connect(self.reject_dialog)
                
            button_layout.addWidget(btn)

        button_layout.addStretch()
        self.main_layout.addWidget(button_container)

        # 添加底部间距
        self.main_layout.addSpacing(15)

    def get_icon_for_type(self):
        """根据消息类型获取图标"""
        icons = {
            self.INFO: "ℹ️",
            self.WARNING: "⚠️", 
            self.ERROR: "❌",
            self.QUESTION: "❓",
            self.SUCCESS: "✅"
        }
        return icons.get(self.msg_type, "ℹ️")

    def apply_glassmorphism_effect(self):
        """应用毛玻璃效果"""
        container = QWidget(self)
        container.setGeometry(0, 0, self.width(), self.height())

        # 根据消息类型设置不同的颜色主题
        if self.msg_type == self.ERROR:
            # 错误消息使用红色主题
            bg_style = """
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(255, 107, 107, 0.4),
                    stop:0.3 rgba(255, 142, 142, 0.35),
                    stop:0.7 rgba(255, 160, 160, 0.32),
                    stop:1 rgba(255, 175, 175, 0.38));
                border: 2px solid rgba(255, 107, 107, 0.5);
            """
        elif self.msg_type == self.WARNING:
            # 警告消息使用橙色主题
            bg_style = """
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(255, 193, 7, 0.4),
                    stop:0.3 rgba(255, 206, 84, 0.35),
                    stop:0.7 rgba(255, 224, 130, 0.32),
                    stop:1 rgba(255, 236, 179, 0.38));
                border: 2px solid rgba(255, 193, 7, 0.5);
            """
        elif self.msg_type == self.SUCCESS:
            # 成功消息使用绿色主题
            bg_style = """
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(76, 175, 80, 0.4),
                    stop:0.3 rgba(129, 199, 132, 0.35),
                    stop:0.7 rgba(165, 214, 167, 0.32),
                    stop:1 rgba(200, 230, 201, 0.38));
                border: 2px solid rgba(76, 175, 80, 0.5);
            """
        else:
            # 默认使用粉色主题
            bg_style = """
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(255, 182, 193, 0.4),
                    stop:0.3 rgba(255, 192, 203, 0.35),
                    stop:0.7 rgba(255, 160, 180, 0.32),
                    stop:1 rgba(255, 175, 190, 0.38));
                border: 2px solid rgba(255, 182, 193, 0.5);
            """

        container.setStyleSheet(f"""
            QWidget {{
                {bg_style}
                border-radius: 22px;
            }}
        """)

        if hasattr(self, 'main_layout'):
            container.setLayout(self.main_layout)

    def get_primary_button_style(self):
        """获取主要按钮样式"""
        return """
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 107, 129, 0.9),
                    stop:0.5 rgba(255, 142, 83, 0.9),
                    stop:1 rgba(255, 175, 123, 0.9));
                color: white;
                border: 2px solid rgba(255, 107, 129, 0.6);
                border-radius: 18px;
                font-size: 15px;
                font-weight: 600;
                font-family: 'Microsoft YaHei UI', sans-serif;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 107, 129, 1.0),
                    stop:0.5 rgba(255, 142, 83, 1.0),
                    stop:1 rgba(255, 175, 123, 1.0));
                border: 2px solid rgba(255, 107, 129, 0.8);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 87, 109, 1.0),
                    stop:0.5 rgba(255, 122, 63, 1.0),
                    stop:1 rgba(255, 155, 103, 1.0));
            }
        """

    def get_secondary_button_style(self):
        """获取次要按钮样式"""
        return """
            QPushButton {
                background: rgba(255, 255, 255, 0.25);
                color: rgba(255, 255, 255, 0.9);
                border: 2px solid rgba(255, 255, 255, 0.4);
                border-radius: 18px;
                font-size: 15px;
                font-weight: 600;
                font-family: 'Microsoft YaHei UI', sans-serif;
            }
            QPushButton:hover {
                background: rgba(255, 255, 255, 0.3);
                color: rgba(255, 255, 255, 0.95);
                border: 2px solid rgba(255, 255, 255, 0.5);
            }
            QPushButton:pressed {
                background: rgba(255, 255, 255, 0.35);
                border: 2px solid rgba(255, 255, 255, 0.6);
            }
        """

    def setup_animations(self):
        """设置动画效果"""
        self.fade_animation = QPropertyAnimation(self, b"windowOpacity")
        self.fade_animation.setDuration(280)
        self.fade_animation.setEasingCurve(QEasingCurve.OutCubic)
        QTimer.singleShot(50, self.start_entrance_animation)

    def start_entrance_animation(self):
        """启动入场动画"""
        self.setWindowOpacity(0)
        self.fade_animation.setStartValue(0.0)
        self.fade_animation.setEndValue(1.0)
        self.fade_animation.start()

    def paintEvent(self, event):
        """自定义绘制事件 - 绘制背景"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 根据消息类型绘制不同颜色的背景渐变
        gradient = QLinearGradient(0, 0, self.width(), self.height())
        
        if self.msg_type == self.ERROR:
            gradient.setColorAt(0, QColor(255, 107, 107, 50))
            gradient.setColorAt(0.5, QColor(255, 142, 142, 60))
            gradient.setColorAt(1, QColor(255, 175, 175, 50))
        elif self.msg_type == self.WARNING:
            gradient.setColorAt(0, QColor(255, 193, 7, 50))
            gradient.setColorAt(0.5, QColor(255, 206, 84, 60))
            gradient.setColorAt(1, QColor(255, 236, 179, 50))
        elif self.msg_type == self.SUCCESS:
            gradient.setColorAt(0, QColor(76, 175, 80, 50))
            gradient.setColorAt(0.5, QColor(129, 199, 132, 60))
            gradient.setColorAt(1, QColor(200, 230, 201, 50))
        else:
            gradient.setColorAt(0, QColor(255, 182, 193, 50))
            gradient.setColorAt(0.5, QColor(255, 192, 203, 60))
            gradient.setColorAt(1, QColor(255, 175, 190, 50))

        painter.fillRect(self.rect(), QBrush(gradient))

        # 绘制装饰圆圈
        self.draw_decorative_circles(painter)

        super().paintEvent(event)

    def draw_decorative_circles(self, painter):
        """绘制装饰性圆圈"""
        painter.setOpacity(0.06)

        # 根据消息类型设置不同的装饰圆圈颜色
        if self.msg_type == self.ERROR:
            color1, color2 = QColor(255, 107, 107), QColor(255, 175, 175)
        elif self.msg_type == self.WARNING:
            color1, color2 = QColor(255, 193, 7), QColor(255, 236, 179)
        elif self.msg_type == self.SUCCESS:
            color1, color2 = QColor(76, 175, 80), QColor(200, 230, 201)
        else:
            color1, color2 = QColor(255, 182, 193), QColor(255, 175, 190)

        # 圆圈1
        gradient1 = QRadialGradient(120, 100, 100)
        gradient1.setColorAt(0, color1)
        gradient1.setColorAt(1, color2)
        painter.setBrush(QBrush(gradient1))
        painter.setPen(Qt.NoPen)
        painter.drawEllipse(50, 40, 200, 200)

        # 圆圈2
        gradient2 = QRadialGradient(400, 200, 120)
        gradient2.setColorAt(0, color2)
        gradient2.setColorAt(1, color1)
        painter.setBrush(QBrush(gradient2))
        painter.drawEllipse(320, 120, 240, 240)

        painter.setOpacity(1.0)

    def accept_dialog(self):
        """接受对话框"""
        self.result_value = True
        self.accept()
    
    def reject_dialog(self):
        """拒绝对话框"""
        self.result_value = False
        self.reject()

    def done_with_result(self, result):
        """完成并返回结果"""
        self.result_value = result
        self.accept() if result else self.reject()

    def get_result(self):
        """获取结果"""
        return self.result_value

    @staticmethod
    def show_info(parent, title, message):
        """显示信息对话框"""
        dialog = GlassmorphismMessageBox(parent, title, message, GlassmorphismMessageBox.INFO)
        return dialog.exec_()

    @staticmethod  
    def show_warning(parent, title, message):
        """显示警告对话框"""
        dialog = GlassmorphismMessageBox(parent, title, message, GlassmorphismMessageBox.WARNING)
        return dialog.exec_()

    @staticmethod
    def show_error(parent, title, message):
        """显示错误对话框"""
        dialog = GlassmorphismMessageBox(parent, title, message, GlassmorphismMessageBox.ERROR)
        return dialog.exec_()

    @staticmethod
    def show_question(parent, title, message):
        """显示询问对话框"""
        dialog = GlassmorphismMessageBox(parent, title, message, GlassmorphismMessageBox.QUESTION, ["取消", "确定"])
        result = dialog.exec_()
        return dialog.get_result()

    @staticmethod
    def show_success(parent, title, message):
        """显示成功对话框"""
        dialog = GlassmorphismMessageBox(parent, title, message, GlassmorphismMessageBox.SUCCESS)
        return dialog.exec_()


# 便捷函数，用于快速替换QMessageBox
def warning(parent, title, message):
    """替换QMessageBox.warning"""
    return GlassmorphismMessageBox.show_warning(parent, title, message)

def critical(parent, title, message):
    """替换QMessageBox.critical"""
    return GlassmorphismMessageBox.show_error(parent, title, message)

def information(parent, title, message):
    """替换QMessageBox.information"""
    return GlassmorphismMessageBox.show_info(parent, title, message)

def question(parent, title, message):
    """替换QMessageBox.question，返回True/False"""
    return GlassmorphismMessageBox.show_question(parent, title, message)

def success(parent, title, message):
    """替换QMessageBox.information，显示成功消息"""
    return GlassmorphismMessageBox.show_success(parent, title, message)
